package net.example.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import net.example.activity.adapter.KeyValuePairAdpter;
import net.example.activity.adapter.ListViewImageTextAdapter;
import net.example.manager.ClientGlobalCache;
import net.example.manager.Manager;
import net.example.manager.GGApplication;
import net.example.model.ImageTextModel;
import net.example.model.KeyValuePairModel;
import net.example.model.GGUser;
import net.example.model.UpdatePropertyType;
import net.example.model.event.FriendCatalogChangedEvent;
import net.example.model.event.FriendCommentNameChangedEvent;
import net.example.model.event.FriendDeletedNotifyEvent;
import net.example.model.event.UserHeadImageChangedEvent;
import net.example.model.event.UserInfoChangedEvent;
import net.example.ggtalk.R;
import net.example.utils.ConfigUtils;
import net.example.utils.HeadImgHelper;
import net.example.utils.IntentUtils;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


public class UserDetailActivity extends Activity {
    private GGUser GGUser_friend;
    private ImageView iv_header;
    private TextView tv_commentName;
    private TextView tv_userName;
    private TextView tv_userID;
    private TextView tv_signature;
    private ListView lv_btnGroup;
    private List<ImageTextModel> models=new ArrayList<ImageTextModel>(){ };
    private List<KeyValuePairModel> keyValuePairModels;
    private KeyValuePairAdpter keyValuePairAdpter;
    private ListView lv_material;
    private boolean isRequesting=false;//正在请求服务中
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_detail);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        this.initView();
    }

    private void initView()
    {
        try {
            String userId = getIntent().getStringExtra("requestID");
            this.iv_header =(ImageView)  findViewById(R.id.avatar);
            this.tv_commentName=(TextView)findViewById(R.id.commentName);
            this.tv_userName =(TextView) findViewById(R.id.userName);
            this.tv_userID=(TextView) findViewById(R.id.userDetail_userID);
            this.tv_signature = (TextView) findViewById(R.id.signature);
            this.tv_signature.setVisibility(View.VISIBLE);
            this.lv_btnGroup= (ListView) findViewById(R.id.btn_listView);
            this.setBaseInfo(userId);
            Boolean isFirend=ClientGlobalCache.getInstance().getCurrentUser().isFriend(userId);
            if(!isFirend||ClientGlobalCache.getInstance().getCurrentUser().isInMyBlackList(GGUser_friend.getUserID()))
            {
                Button btn_del=(Button)findViewById(R.id.btn_del);
                btn_del.setVisibility(View.GONE);
            }
            this.initBtnListView(isFirend);
            if(isFirend)
            {
                this.initMaterialListView();
            }
        }catch (Exception ex){ex.printStackTrace();}

    }

    //    初始化按钮数据
    private void initBtnListView(final boolean isFirend)
    {
        if(ClientGlobalCache.getInstance().getCurrentUser().isInMyBlackList(GGUser_friend.getUserID()))
        {
            return;
        }
        if(isFirend)
        {
            models.add(new ImageTextModel(R.drawable.send_icon, "发送消息", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    IntentUtils.startActivityForString_Dubble(UserDetailActivity.this, ChatActivity.class, ConfigUtils.TalkingType, ConfigUtils.Person_Talking, ConfigUtils.Person_Talking, GGUser_friend.getUserID());

                }
            }));
            models.add( new ImageTextModel(R.drawable.video_icon, "视频聊天", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    IntentUtils.startActivityForString(view.getContext(), VideoCallActivity.class, "requestID", GGUser_friend.getUserID());
                }
            }));
        }
        else
        {
            models.add(new ImageTextModel(0, "加好友", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(isRequesting)
                    {
                        return;
                    }
                    isRequesting=true;
                    String catalogName= getResources().getString(R.string.friend_catalog_name);
                    IntentUtils.startActivityForString(UserDetailActivity.this, AddFriendOrGroupApplyActivity.class,"friendID", GGUser_friend.getUserID());
                }
            }));
        }
        ListViewImageTextAdapter btnGroupAdapter=new ListViewImageTextAdapter(this.models,this);
        lv_btnGroup.setAdapter(btnGroupAdapter);
    }

    private void setBaseInfo(String userID)
    {
        this.GGUser_friend =ClientGlobalCache.getInstance().getUser(userID);
        HeadImgHelper.setUserHeadImg(iv_header,this.GGUser_friend);
        this.tv_commentName.setText(this.GGUser_friend.getCommentName());
        this.tv_userID.setText("账号：" + this.GGUser_friend.getUserID());
        this.tv_userName.setText("名称："+this.GGUser_friend.getName());
        this.tv_signature.setText("签名：" + this.GGUser_friend.getSignature());
    }

    private void initMaterialListView() {
        lv_material = (ListView) findViewById(R.id.material_listView);
        keyValuePairModels = new ArrayList<>();
        keyValuePairModels.add(new KeyValuePairModel(R.drawable.grouping_icon,getResources().getString(R.string.Catalog), ClientGlobalCache.getInstance().getCurrentUser().getCatalogNameByFriend(GGUser_friend.getUserID())));
        keyValuePairModels.add(new KeyValuePairModel(R.drawable.autograph_icon,"备注", GGUser_friend.getCommentName()));
        keyValuePairAdpter = new KeyValuePairAdpter(keyValuePairModels, this,true);
        lv_material.setAdapter(keyValuePairAdpter);
        lv_material.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> adapterView,View view,int position,long id)
            {
                KeyValuePairModel model=keyValuePairModels.get(position);
                try {
                    if(model.Key.equals(getResources().getString(R.string.Catalog)))
                    {
                        IntentUtils.startActivityForString_Dubble(UserDetailActivity.this,FriendCatalogActivity.class,"friendID", GGUser_friend.getUserID(),getResources().getString(R.string.Catalog),ClientGlobalCache.getInstance().getCurrentUser().getCatalogNameByFriend(GGUser_friend.getUserID()));
                    }
                    else if(model.Key.equals("备注"))
                    {
                        IntentUtils.startActivityForString_Dubble(UserDetailActivity.this,UpdatePropertyActivity.class, getResources().getString(R.string.update_property_type), UpdatePropertyType.FriendCommentName.toString(),
                                getResources().getString(R.string.property_entity), GGUser_friend.getUserID());
                    }
                }catch (Exception ee) {
                    ee.printStackTrace();
                }
            }
        });
    }

    //刷新资料组
    private void refresh_lv_material()
    {
        for (KeyValuePairModel model:keyValuePairModels) {
            if(model.Key.equals(getResources().getString(R.string.Catalog)))
            {
                model.Value=ClientGlobalCache.getInstance().getCurrentUser().getCatalogNameByFriend(GGUser_friend.getUserID());
            }
        }
        keyValuePairAdpter.notifyDataSetChanged();
    }

    public void onEventMainThread(UserInfoChangedEvent event)
    {
        if(event.UserID.equals(this.GGUser_friend.getUserID()))
        {
            this.setBaseInfo(event.UserID);
        }
    }

    public void onEventMainThread(UserHeadImageChangedEvent event){
        if(event.UserID.equals(this.GGUser_friend.getUserID()))
        {
            this.setBaseInfo(event.UserID);
        }
    }

    public void onEventMainThread(FriendCatalogChangedEvent event)
    {
        this.refresh_lv_material();
    }

    public void onEventMainThread(FriendCommentNameChangedEvent event)
    {
        if(event.FriendID.equals(this.GGUser_friend.getUserID()))
        {
            this.tv_commentName.setText(event.CommentName);
            for(int i=0;i<keyValuePairModels.size();i++)
            {
                if(keyValuePairModels.get(i).Key.equals("备注"))
                {
                    keyValuePairModels.get(i).Value=event.CommentName;
                    keyValuePairAdpter.notifyDataSetChanged();
                }
            }
        }

    }

    public void finish(View view) {
        finish();
    }

    public void delete(View view)
    {
        this.showNormalDialog();
    }

    private void showNormalDialog() {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(UserDetailActivity.this);
        normalDialog.setTitle("提示");
        normalDialog.setMessage("您确定要删除好友[" + this.GGUser_friend.getName() + "]吗？");
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Manager.getInstance().removeFriend(GGUser_friend.getUserID());
                        EventBus.getDefault().post(new FriendDeletedNotifyEvent(GGUser_friend, true));
                        IntentUtils.startActivity(UserDetailActivity.this, MainActivity.class);
//                        Intent intent = new Intent(UserDetailActivity.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                        startActivity(intent);
                    }
                });

        // 显示
        normalDialog.show();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
